package com.rico.kok.config;

import com.rico.kok.entity.User;
import com.rico.kok.service.interf.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //新建示例型授权对象
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        //为认证用户添加角色
        simpleAuthorizationInfo.addRole("user");
        //返回授权信息
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户账号
        String principle= (String) authenticationToken.getPrincipal();
        //在数据库中检查用户是否存在
        List<User> users = userService.selectUsers(new User(principle));
        //存在的话进行下一步认证
        if (users.size()>0){
            //进行密码校验
            SimpleAuthenticationInfo simpleAuthenticationInfo=
                    new SimpleAuthenticationInfo(principle,users.get(0).getUserPassword(), ByteSource.Util.bytes(users.get(0).getSalt()),this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
